package com.zhanglijie.improve.atomic.four;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/9/8 0008 0:24
 */
public class TestSafeRefenceSolve {


    static MyCount myCount = new  MyCount(0);
    // static MySafeRefence<MyCount> testInnerUnsafeRefenceSolve = new MySafeRefence<MyCount>("money",(Class<MyCount>) myCount.getClass());
    //使用jdk的AtomicIntegerFieldUpder 穿的属性必须不能private修饰
    static AtomicIntegerFieldUpdater<MyCount> testInnerUnsafeRefenceSolve =   AtomicIntegerFieldUpdater.newUpdater((Class<MyCount>) myCount.getClass(),"money");



    public static void main(String[] args) throws NoSuchFieldException, InterruptedException {

        TestSafeRefenceSolve test = new TestSafeRefenceSolve();
        CountDownLatch countDownLatch = new CountDownLatch(10000);
        for (int i = 0; i <10000; i++) {
            int finalI = i;
            new Thread(()->{
                test.plus(1);
                countDownLatch.countDown();
            }).start();

        }
         countDownLatch.await();
         System.out.println(myCount.money);//应该是5050  但是有时候会出现4975之类不是5050的值
    }

    static class MyCount{
        volatile int money;// 这个volatile必须加，

        @Override
        public String toString() {
            return "MyCount{" + "money=" + money + '}';
        }

        public int getMoney() {
            return money;
        }

        public MyCount(int money) {
            this.money = money;
        }

        public void setMoney(int money) {
            this.money = money;
        }
    }
    public void plus(int num){
        testInnerUnsafeRefenceSolve.addAndGet(myCount,num);
    }
}
